package com.solusiq.me.db;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;


/**
 *  An example (an abstraction) of Recordable interface.
 * 
 *  The most unique things on record implementation is the data serialization proccess.
 *  The rest methods on Recordable interface, mostly, implements in the same way.
 *  
 *  You can choose whether extending this class or implement the Recordable interface. 
 * 
 * @author Amru Mubaidillah
 *
 */
public abstract class AbstractRecord implements Recordable {

	private int recordId;
	
	public void setRecordId(int newId) {
		this.recordId = newId;
	}

	public int getRecordId() {
		return recordId;
	}

	public byte[] serialize() {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream outputStream = new DataOutputStream(baos);
		try {
			doWrite(outputStream);
			outputStream.close();
		} catch (IOException ioe) {
		}
		
		return baos.toByteArray();
	}

	public void unserialize(byte[] data) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		DataInputStream inputStream = new DataInputStream(bais);
		try {
			doRead(inputStream);
			inputStream.close();
		}
		catch (EOFException eofe) {
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
